/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.mlbs.utility;

import java.io.IOException;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

/**
 *
 * @author mckd87
 */
public class GoogleParser extends org.xml.sax.helpers.DefaultHandler{
    
        private SAXParserFactory factory;
        private SAXParser saxParser;
        private InputSource source;
        
        private ArrayList results;
        private String node ;
        private boolean titleTag;
        
	private void initParser(java.io.InputStream is){
		//XMLReader xr = null;
		try {
                    results = new ArrayList();
                    factory = SAXParserFactory.newInstance();
                    factory.setValidating(false);
                    saxParser = factory.newSAXParser();
                    source = new org.xml.sax.InputSource(is);
                    XMLReader reader = saxParser.getXMLReader();
                    reader.setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (Exception e) {
                        e.printStackTrace();
                }

	}


    public void parseXML(){
        try {
            saxParser.parse(this.source ,this);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
        
    
    public GoogleParser(java.io.InputStream is)
    {
	super();
	initParser(is);
    }


    @Override
    public void startDocument ()
    {
    }


    public void endDocument ()
    {
    }


    @Override
    public void startElement (String uri, String name, String qName, Attributes atts)
    {
	if(qName.equalsIgnoreCase("title")){
            titleTag = true;
        }
    }


    @Override
    public void endElement (String uri, String name, String qName)
    {
	if(qName.equalsIgnoreCase("item")){
            results.add(node);
	}else if(qName.equalsIgnoreCase("title")){
            titleTag = false;
        }
    }


    @Override
    public void characters (char buf[], int offset, int len)
    {
        String s = new String (buf, offset, len); 
        //System.out.println(s);
        if (s.indexOf("\n") < 0 && s.length () > 0) {  
            if(titleTag){
                node = s;
            }
        }
    }
    
    public ArrayList getResults(){
        return results;
    }
}
